package com.liuhm.controller;

import com.liuhm.conf.MinioConfig;
import com.liuhm.exception.R;
import com.liuhm.service.MinioService;
import io.minio.messages.Bucket;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * minio上传的控制层
 *
 * @author liuhaomin
 * @date 2020/8/18
 */
@RequestMapping("/minio")
@RestController
@Api(tags = "文件上传接口")
public class MinioController {

    @Autowired
    private MinioService minioService;

    @Autowired
    private MinioConfig minioConfig;

    @ApiOperation(value = "使用minio文件上传")
    @PostMapping("/uploadFile")
    public R uploadFile(@ApiParam(name = "file", value = "上传的文件", required = true) @RequestParam("file") MultipartFile file,@ApiParam(name = "bucketName", value = "对象存储桶名称") @RequestParam(value = "bucketName",required = false) String bucketName,@ApiParam(name = "isPublic", value = "对象存储桶的策略 是否是公共的文件桶") @RequestParam(value = "isPublic",required = false) Boolean isPublic) {
        try {
            bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            if (!minioService.bucketExists(bucketName)) {
                minioService.makeBucket(bucketName);
            }
            if (isPublic!=null&&isPublic==true) {
                String policy="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::"+bucketName+"\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\"],\"Resource\":[\"arn:aws:s3:::"+bucketName+"/*\"]}]}";
                minioService.setBucketPolicy(bucketName,policy);
            }
            String fileName = file.getOriginalFilename();
            String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));

            InputStream inputStream = file.getInputStream();
            minioService.putObject(bucketName, objectName, inputStream);
            inputStream.close();
            return R.ok(minioService.getObjectUrl(bucketName, objectName));
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("上传失败");
        }
    }

    @ApiOperation(value = "删除minio文件")
    @DeleteMapping("/deleteFile")
    public R deleteFile(@ApiParam(name = "objectName", value = "上传的文件的全路径", required = true) @RequestParam("objectName") String objectName,@ApiParam(name = "bucketName", value = "对象存储桶名称") @RequestParam(value = "bucketName",required = false)  String bucketName) {
        try {
            bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            return R.ok( minioService.removeObject(bucketName, objectName));
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("删除失败");
        }
    }
    @ApiOperation(value = "下载minio文件")
    @PostMapping("/downloadFile")
    public R downloadFile(@ApiParam(name = "bucketName", value = "对象存储桶名称", required = false) @RequestParam(value = "bucketName",required = false) String bucketName, @ApiParam(name = "fileName", value = "文件路径",required = true) @RequestParam(value = "fileName") String fileName,HttpServletResponse response) {
        try {
            bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            minioService.downloadFile(bucketName, fileName,response);
            return R.ok( );
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("删除失败");
        }
    }

    @ApiOperation(value = "列出所有存储桶")
    @GetMapping("/listBuckets")
    public R listBuckets() {
        try {
            List<Bucket> bucketList=minioService.listBuckets();
            return R.ok(bucketList.stream().map(Bucket::name).toArray());
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("列出所有存储桶失败");
        }
    }

    @ApiOperation(value = "列出存储桶中的所有对象名称")
    @GetMapping("/listObjectNames")
    public R listObjectNames(@ApiParam(name = "bucketName", value = "对象存储桶名称", required = true) @RequestParam(value = "bucketName") String bucketName) {
        try {
            return R.ok(minioService.listObjectNames(bucketName));
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("列出存储桶中的所有对象名称失败");
        }
    }
    @ApiOperation(value = "获取存储桶的策略")
    @GetMapping("/getBucketPolicy")
    public R getBucketPolicy(@ApiParam(name = "bucketName", value = "对象存储桶名称", required = true) @RequestParam(value = "bucketName") String bucketName) {
        try {
            return R.ok(minioService.getBucketPolicy(bucketName));
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("获取存储桶的策略失败");
        }
    }
    @ApiOperation(value = "获取文件链接")
    @GetMapping("/presignedGetObject")
    public R presignedGetObject(@ApiParam(name = "bucketName", value = "对象存储桶名称", required = true) @RequestParam(value = "bucketName") String bucketName,@ApiParam(name = "objectName", value = "存储桶里的对象名称", required = true) @RequestParam(value = "objectName") String objectName,@ApiParam(name = "expires", value = "过期时间") @RequestParam(value = "expires",required = false) Integer expires) {
        try {
            expires=expires!=null? expires : (60 * 60 * 24 * 7);
            return R.ok(minioService.presignedGetObject(bucketName,objectName,expires));
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("获取存储桶的策略失败");
        }
    }


}